package knowledge

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"time"
)

// APISource represents an API documentation source
type APISource struct {
	config      *SourceConfig
	client      *http.Client
	lastUpdated time.Time
	cache       map[string]*Document
}

// NewAPISource creates a new API documentation source
func NewAPISource(config *SourceConfig) *APISource {
	return &APISource{
		config: config,
		client: &http.Client{
			Timeout: time.Second * 30,
		},
		cache: make(map[string]*Document),
	}
}

// ID implements Source interface
func (s *APISource) ID() string {
	return s.config.ID
}

// Type implements Source interface
func (s *APISource) Type() string {
	return string(s.config.Type)
}

// Fetch implements Source interface
func (s *APISource) Fetch(ctx context.Context, query string) ([]*Document, error) {
	// Check cache first
	if doc, ok := s.cache[query]; ok {
		return []*Document{doc}, nil
	}

	// Fetch from API
	req, err := http.NewRequestWithContext(ctx, "GET",
		fmt.Sprintf("%s/docs?q=%s", s.config.URL, query),
		nil)
	if err != nil {
		return nil, err
	}

	// Add credentials
	for k, v := range s.config.Credentials {
		req.Header.Add(k, v)
	}

	resp, err := s.client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var docs []*Document
	if err := json.NewDecoder(resp.Body).Decode(&docs); err != nil {
		return nil, err
	}

	// Update cache
	for _, doc := range docs {
		s.cache[doc.ID] = doc
	}

	return docs, nil
}

// Update implements Source interface
func (s *APISource) Update(ctx context.Context) error {
	// Clear cache
	s.cache = make(map[string]*Document)

	// Fetch latest docs
	_, err := s.Fetch(ctx, "") // 修改为忽略返回值
	if err != nil {
		return err
	}

	s.lastUpdated = time.Now()
	return nil
}

// LastUpdated implements Source interface
func (s *APISource) LastUpdated() time.Time {
	return s.lastUpdated
}
